package cn.org.book.shop.app.service;

import cn.org.book.shop.article.domain.ApUser;
import cn.org.book.shop.article.mapper.ApUserMapper;
import cn.org.book.shop.common.utils.http.HttpUtils;
import cn.org.book.shop.config.AppConfig;
import cn.org.book.shop.message.UserInfoBean;
import cn.org.book.shop.utils.AppConstant;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.List;
import java.util.UUID;

/**
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-12-05 21:23
 * @Description:
 */
@Slf4j
@Service
public class UserInfoService {

    @Resource
    private AppConfig appConfig;

    @Resource
    private ApUserMapper userMapper;

    /**
     * 根据设备ID获取用户信息
     *
     * @param deviceId 设备ID
     * @return
     */
    public ApUser selectUserInfoByDeviceId(String deviceId) {
        ApUser apUser = new ApUser();
        apUser.setDeviceId(deviceId);
        List<ApUser> apUsers = userMapper.selectApUserList(apUser);
        if (null == apUsers || apUsers.isEmpty()) {
            return null;
        } else {
            return apUsers.get(0);
        }
    }


    public String saveUserInfo(UserInfoBean userInfoBean) {
        String result = getSessionKey(userInfoBean.getCode());
        String sessionKey = JSONObject.parseObject(result).getString(AppConstant.SESSION_KEY);
        String openId = JSONObject.parseObject(result).getString(AppConstant.OPENID);
        String unionId = JSONObject.parseObject(result).getString(AppConstant.UNIONID);
        ApUser userInfo = userInfoBean.getUserInfo();
        userInfo.setOpenId(openId);
        userInfo.setUnionId(unionId);
        String wxUserInfo = getWxUserInfo(userInfoBean.getIv(), sessionKey, userInfoBean.getEncryptedData());
        log.info("wxUserInfo is [{}]", wxUserInfo);
        List<ApUser> apUsers = userMapper.selectApUserList(userInfo);
        userInfo.setDeviceId(UUID.randomUUID().toString().replaceAll("-", ""));
        if (null == apUsers || apUsers.isEmpty()) {
            userMapper.insertApUser(userInfo);
        } else {
            userInfo = apUsers.get(0);
        }
        return userInfo.getDeviceId();
    }

    /**
     * 获取sessionKey
     *
     * @param code 登陆授权码
     */
    public String getSessionKey(String code) {
        return HttpUtils.sendGet(AppConstant.getUrlGetSessionKey(appConfig.getAppId(), appConfig.getSecret(), code), null);
    }

    public String getWxUserInfo(String iv, String session, String encrypt) {
        // 获取参数
        byte[] byEncryptData = Base64.decodeBase64(encrypt);
        byte[] byIvData = Base64.decodeBase64(iv);
        byte[] bySessionKey = Base64.decodeBase64(session);
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec keySpec = new SecretKeySpec(bySessionKey, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(byIvData));
            return new String(cipher.doFinal(byEncryptData), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("getWxUserInfo is error", e);
            return null;
        }
    }

}
